package cn.iocoder.devlop.module.annual.report.record.service;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.devlop.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.devlop.module.annual.report.record.controller.vo.ReportRecordBaseVO;
import cn.iocoder.devlop.module.annual.report.record.convert.ReportRecordConvert;
import cn.iocoder.devlop.module.annual.report.record.dal.ReportRecordMapper;
import cn.iocoder.devlop.module.annual.report.record.dal.dataobject.ReportRecordDO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 年报记录信息 Service 实现类
 *
 * @author sunhao
 */
@Service
@Validated
@RequiredArgsConstructor
public class ReportRecordServiceImpl implements ReportRecordService {

    private final ReportRecordMapper reportRecordMapper;

    @Override
    public ReportRecordDO getRecord(ReportRecordBaseVO baseVO) {
        LambdaQueryWrapperX<ReportRecordDO> lambdaQueryWrapperX = new LambdaQueryWrapperX<>();
        lambdaQueryWrapperX.eq(ReportRecordDO::getRegno, baseVO.getRegno());
        lambdaQueryWrapperX.eq(ReportRecordDO::getYear, baseVO.getYear());
        return reportRecordMapper.selectOne(lambdaQueryWrapperX);
    }

    @Override
    public void saveRecord(ReportRecordBaseVO baseVO) {
        if("1".equals(baseVO.getIsImp())){
            deleteRecord(baseVO);
        }
        ReportRecordDO record = getRecord(baseVO);
        if (ObjUtil.isEmpty(record)) {
            reportRecordMapper.insert(ReportRecordConvert.INSTANCE.convert(baseVO));
        } else {
            ReportRecordDO reportRecordDO = ReportRecordConvert.INSTANCE.convert(baseVO);
            List<String> fillingItem  = Arrays.stream(record.getFillingItem().split(",")).collect(Collectors.toList());
            if (!fillingItem.contains(baseVO.getFillingItem())) {
                String filling = StrUtil.join(",", fillingItem, baseVO.getFillingItem());
                reportRecordDO.setFillingItem(filling);
                LambdaQueryWrapperX<ReportRecordDO> lambdaQueryWrapperX = new LambdaQueryWrapperX<>();
                lambdaQueryWrapperX.eq(ReportRecordDO::getRegno, baseVO.getRegno());
                lambdaQueryWrapperX.eq(ReportRecordDO::getYear, baseVO.getYear());
                reportRecordMapper.update(reportRecordDO, lambdaQueryWrapperX);
            }
        }
    }

    private void deleteRecord(ReportRecordBaseVO baseVO){
        LambdaQueryWrapperX<ReportRecordDO> wrapperX = new LambdaQueryWrapperX<>();
        wrapperX.eq(ReportRecordDO::getRegno,baseVO.getRegno());
        wrapperX.eq(ReportRecordDO::getYear,baseVO.getYear());
        reportRecordMapper.delete(wrapperX);
    }

}
